

import { EggAppConfig, PowerPartial } from 'egg';
import * as fs from 'fs';
import * as path from 'path';

// for config.{env}.ts
export type DefaultConfig = PowerPartial<EggAppConfig & BizConfig>;

// app special config scheme
export interface BizConfig {
  sourceUrl: string;
  news: {
    pageSize: number;
    serverUrl: string;
  };
}

export default (appInfo: EggAppConfig) => {
  const config = {} as PowerPartial<EggAppConfig> & BizConfig;

  // app special config
  config.sourceUrl = `https://github.com/eggjs/examples/tree/master/${appInfo.name}`;
  config.news = {
    pageSize: 30,
    // serverUrl: 'https://hacker-news.firebaseio.com/v0',
    serverUrl: 'http://127.0.0.1:7001/public',
  };

  // override config from framework / plugin
  config.keys = appInfo.name + '123456';

  config.view = {
    defaultViewEngine: 'nunjucks',
    mapping: {
      '.tpl': 'nunjucks',
      '.html': 'nunjucks',
    },
  };

  config.siteFile = {
    '/favicon.ico': fs.readFileSync(path.join(appInfo.baseDir, 'app/public/favicon.png')),
  };

  // config/config.defaullt.ts
  config.sequelize = {
    dialect: 'mysql', // 表示是mysql数据库
    host: '127.0.0.1',
    port: 3306,
    database: 'egg-blog',
    username: 'root',
    password: '123456',
    timezone: '+08:00', // 表示为东八区的时间
  };

  config.mysql = {
    // 单数据库信息配置
    client: {
      host: 'localhost',
      port: '3306',
      user: 'root',
      password: '123456',
      database: 'test',
    },
    app: true,
    agent: false,
  };

  config.security = {
    csrf: {
      enable: false,
    },
    // domainWhiteList: '*'  // 白名单
  };
  config.cors = {
    origin: ctx => ctx.get('origin'),
    credentials: true,
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
  };
  config.jwt = {
    secret: '123456ee', // 自定义 token 的加密条件字符串
  };

  config.middleware = [ 'jwtAuth', 'errorHandler', 'manageAuth' ];
  config.jwtAuth = {

    // whiteUrls: ['/test'], // 是使用url的前缀匹配的
    // 不需要登录的页面，白名单URL
    // 也可以使用
    // ignore: [ '/home', '/api/v1/test/', '/public/', '/manage/' ],
    match: '/api/v1/user',
  };
  config.manageAuth = {
    match: '/manage/',
  };
  config.session = {
    key: 'SESSION_ID',
    maxAge: 1000 * 60 * 30,
    httpOnly: true,
    encrypt: true,
    renew: true,
  };

  return config;
};
